package com.walkline.screen;

import java.util.Hashtable;
import java.util.Vector;

import localization.WeiboSDKResource;
import net.rim.blackberry.api.browser.Browser;
import net.rim.blackberry.api.browser.BrowserSession;
import net.rim.device.api.i18n.ResourceBundle;
import net.rim.device.api.system.Characters;
import net.rim.device.api.system.Display;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.MenuItem;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.Menu;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.decor.BackgroundFactory;
import net.rim.device.api.ui.menu.SubMenu;
import net.rim.device.api.util.StringProvider;

import com.walkline.util.Enumerations.RefreshAction;
import com.walkline.util.Enumerations.RemindType;
import com.walkline.util.Enumerations.ShowStatusImage;
import com.walkline.util.Function;
import com.walkline.util.container.ForegroundManager;
import com.walkline.util.container.StatusListStyleButtonSet;
import com.walkline.util.container.VerticalButtonFieldSet;
import com.walkline.util.me.regexp.RE;
import com.walkline.util.network.DownloadStatusAvatarImages;
import com.walkline.util.network.DownloadStatusImages;
import com.walkline.util.network.WorkQueue;
import com.walkline.util.ui.StatusListStyleButtonField;
import com.walkline.weibo.BasicAsyncCallback;
import com.walkline.weibo.WeiboSDK;
import com.walkline.weibo.inf.Comment;
import com.walkline.weibo.inf.CommentWrapper;
import com.walkline.weibo.inf.Favorite;
import com.walkline.weibo.inf.FavoriteWrapper;
import com.walkline.weibo.inf.Status;
import com.walkline.weibo.inf.StatusWrapper;

public class ShowStatusesMainScreen extends MainScreen implements WeiboSDKResource
{
	private static ResourceBundle _bundle = ResourceBundle.getBundle(BUNDLE_ID, BUNDLE_NAME);

	private WeiboSDK _weibo;
	private WorkQueue _queueAvatar = new WorkQueue(2);
	private WorkQueue _queueImage = new WorkQueue(2);
	private ForegroundManager _foreground = new ForegroundManager(0);
	private StatusListStyleButtonSet _listSet = new StatusListStyleButtonSet();
	private ButtonField _btnMore = new ButtonField("更多", ButtonField.CONSUME_CLICK | ButtonField.NEVER_DIRTY);
	private VerticalButtonFieldSet vbf = new VerticalButtonFieldSet(USE_ALL_WIDTH);
	private static boolean needSmallIcon = Display.getWidth() < 640 ? true : false;

	private int _action = 0;
	private Hashtable _params = new Hashtable();
	private int _current_page = 0;
	private String _max_id = "0";
	private static int _lastMovementTime = 0;
	private String _remindType = "";

	private StatusWrapper _statusWrapper;

	public ShowStatusesMainScreen(WeiboSDK weibo, final Hashtable params, int action)
	{
		super(NO_VERTICAL_SCROLL | USE_ALL_HEIGHT | NO_SYSTEM_MENU_ITEMS);

		getMainManager().setBackground(BackgroundFactory.createSolidBackground(Color.BLACK));

		_weibo = weibo;
		_params = params;
		_action = action;

		_listSet.setMargin(0, -1, 0, -1);

		HorizontalFieldManager hfmTitle = new HorizontalFieldManager(FIELD_HCENTER);
		hfmTitle.add(new LabelField((String) params.get("title")));
		setTitle(hfmTitle);

		_btnMore.setChangeListener(new FieldChangeListener()
		{
			public void fieldChanged(Field field, int context)
			{
				refreshNextPage();
			}
		});					
		vbf.add(_btnMore);

		UiApplication.getUiApplication().invokeLater(new Runnable()
		{
			public void run()
			{
				switch (_action)
				{
					case RefreshAction.STATUSMENTIONS:
						refreshStatusMentions(params);
						break;
					case RefreshAction.COMMENTMENTIONS:
						refreshCommentMentions(params);
						break;
					case RefreshAction.COMMENTTOME:
						refreshCommentToMe(params);
						break;
					case RefreshAction.COMMENTBYME:
						refreshCommentByMe(params);
						break;
					case RefreshAction.PUBLICTIMELINE:
						refreshPublicTimeline(params);
						break;
					case RefreshAction.FRIENDSTIMELINE:
						refreshFriendTimeline(params);
						break;
					case RefreshAction.GROUPTIMELINE:
						refreshGroupTimeline(params);
						break;
					case RefreshAction.USERTIMELINE:
						refreshUserTimeline(params);
						break;
					case RefreshAction.FAVORITES:
						_current_page = 1;
						refreshFavorites(params);
						break;
					case RefreshAction.FAVORITESBYTAGS:
						_current_page = 1;
						refreshFavorites(params);
				}
			}
		});
	}

	private void refreshStatusMentions(Hashtable params) {getStatuses(params);}

	private void refreshCommentMentions(Hashtable params) {getComments(params);}

	private void refreshCommentToMe(Hashtable params) {getComments(params);}

	private void refreshCommentByMe(Hashtable params) {getComments(params);}

	private void refreshPublicTimeline(Hashtable params) {getStatuses(params);}

	private void refreshFriendTimeline(Hashtable params) {getStatuses(params);}

	private void refreshGroupTimeline(Hashtable params) {getStatuses(params);}

	private void refreshUserTimeline(Hashtable params) {getStatuses(params);}

	private void refreshFavorites(Hashtable params) {getFavorites(params);}

	private void getStatuses(final Hashtable params)
	{
		UiApplication.getUiApplication().invokeLater(new Runnable()
		{
			public void run()
			{
				RefreshContentsScreen popupScreen = new RefreshContentsScreen(_weibo, params, _action);
				UiApplication.getUiApplication().pushModalScreen(popupScreen);

				StatusWrapper statusWrapper = popupScreen.getStatusWrapper();

				if (popupScreen != null) {popupScreen = null;}
				if (statusWrapper != null)
				{
					resetReminds();

					_statusWrapper = statusWrapper; refreshContents(statusWrapper, null, null);
				}				
			}
		});
	}

	private void getFavorites(final Hashtable params)
	{
		UiApplication.getUiApplication().invokeLater(new Runnable()
		{
			public void run()
			{
				RefreshContentsScreen popupScreen = new RefreshContentsScreen(_weibo, params, _action);
				UiApplication.getUiApplication().pushModalScreen(popupScreen);

				FavoriteWrapper favoriteWrapper = popupScreen.getFavoriteWrapper();

				if (popupScreen != null) {popupScreen = null;}
				if (favoriteWrapper != null) {refreshContents(null, null, favoriteWrapper);}				
			}
		});
	}

	private void getComments(final Hashtable params)
	{
		UiApplication.getUiApplication().invokeLater(new Runnable()
		{
			public void run()
			{
				RefreshContentsScreen popupScreen = new RefreshContentsScreen(_weibo, params, _action);
				UiApplication.getUiApplication().pushModalScreen(popupScreen);

				CommentWrapper commentWrapper = popupScreen.getCommentWrapper();

				if (popupScreen != null) {popupScreen = null;}
				if (commentWrapper != null)
				{
					resetReminds();

					refreshContents(null, commentWrapper, null);
				}				
			}
		});
	}

	private void resetReminds()
	{
		switch (_action)
		{
			case RefreshAction.FRIENDSTIMELINE:
				_weibo.getReminds().setStatus(0);
				break;
			case RefreshAction.STATUSMENTIONS:
				_remindType = RemindType.MENTION_STATUS;
				break;
			case RefreshAction.COMMENTTOME:
				_remindType = RemindType.CMT;
				break;
			case RefreshAction.COMMENTMENTIONS:
				_remindType = RemindType.MENTION_CMT;
				break;
			default:
				return;
		}

		if (_max_id.equals("0"))
		{
			UiApplication.getUiApplication().invokeLater(new Runnable()
			{
				public void run()
				{
					_weibo.setRemindCount(_remindType, new SetRemindsCountCallback(), null);
				}
			});						
		}
	}

	class SetRemindsCountCallback extends BasicAsyncCallback
	{
		public void onComplete(final boolean value, Object state)
		{
			if (value)
			{
				switch (_action)
				{
					case RefreshAction.STATUSMENTIONS:
						_weibo.getReminds().setMentionStatus(0);
						break;
					case RefreshAction.COMMENTMENTIONS:
						_weibo.getReminds().setMentionCmt(0);
						break;
					case RefreshAction.COMMENTTOME:
						_weibo.getReminds().setCmt(0);
						break;
				}
			}
		}

		public void onException(Exception e, Object state) {Function.errorDialog(e.toString());}
	}

	/**
	 * 加载下一页内容
	 */
	private void refreshNextPage()
	{
		_current_page += 1;
		_params.remove("page");
		_params.remove("max_id");
		_params.put("page", String.valueOf(_current_page));
		_params.put("max_id", _max_id);

		if (isStatusObject())
		{
			getStatuses(_params);
		} else if (isCommentObject()) {
			getComments(_params);
		} else if (isFavoriteObject()) {
			getFavorites(_params);
		}
 	}

	/**
	 * 刷新首页内容
	 */
	private void refreshHomePage()
	{
		_current_page = isFavoriteObject() ? 1 : 0;
		_max_id = "0";

		if (_listSet.getManager() != null) {_listSet.deleteAll();}

		_params.remove("page");
		_params.remove("max_id");
		_params.put("page", "1");
		_params.put("max_id", "0");

		if (isStatusObject())
		{
			getStatuses(_params);
		} else if (isCommentObject()) {
			getComments(_params);
		} else {
			getFavorites(_params);
		}
	}

	private void refreshContents(final StatusWrapper statusWrapper, final CommentWrapper commentWrapper, final FavoriteWrapper favoriteWrapper)
	{
		Vector contents = (statusWrapper != null ? statusWrapper.getStatuses() : commentWrapper != null ? commentWrapper.getComments() : favoriteWrapper.getFavorites());
		StatusListStyleButtonField item;
		StatusListStyleButtonField lastItem = null;

		if (contents.size() > 0)
		{
			if (_listSet.getManager() == _foreground) {_foreground.delete(_listSet);}
			if (_listSet.getFieldCount() > 0)
			{
				if (_listSet.getField(_listSet.getFieldCount() - 1) == vbf) {_listSet.delete(vbf);}
				lastItem = (StatusListStyleButtonField) _listSet.getField(_listSet.getFieldCount() - 1);
			}

			if (statusWrapper != null)
			{
				Status status = null;
				for (int i=0; i<contents.size(); i++)
				{
					status = (Status) contents.elementAt(i);
					item = new StatusListStyleButtonField(_weibo.getAppConfig(), status, false);
					_listSet.add(item);
				}
				if (_max_id.equals("0")) {_max_id = status.getIdStr();}						
			} else if (commentWrapper != null) {
				Comment comment = null;
				for (int i=0; i<contents.size(); i++)
				{
					comment = (Comment) contents.elementAt(i);
					item = new StatusListStyleButtonField(_weibo.getAppConfig(), comment);
					_listSet.add(item);
				}
				if (_max_id.equals("0")) {_max_id = comment.getIdStr();}
			} else {
				Favorite favorite = null;
				for (int i=0; i<contents.size(); i++)
				{
					favorite = (Favorite) contents.elementAt(i);
					item = new StatusListStyleButtonField(_weibo.getAppConfig(), favorite.getStatus(), false);
					if (item.getUser() != null) {_listSet.add(item);}
				}
			}

			if (_foreground.getManager() == null) {add(_foreground);}
			if (_listSet.getManager() != _foreground) {_foreground.add(_listSet);}
			if (lastItem != null) {_listSet.setFieldWithFocus(lastItem);}

			if (_listSet.getFieldCount() > 0)
			{
				UiApplication.getUiApplication().invokeLater(new Runnable()
				{
					public void run()
					{
						if (vbf.getManager() != _listSet)
						{
							_listSet.add(vbf);
						} else {
							_listSet.delete(vbf);
							_listSet.add(vbf);
						}

						if (_listSet.getFieldCount() > 0 && _listSet.getFieldWithFocusIndex() < _listSet.getFieldCount() && _listSet.getFieldWithFocusIndex() != 0)
		    			{
		    				_listSet.getField(_listSet.getFieldWithFocusIndex() + 1).setFocus();
		    			}

						refreshUserListIcons();

						switch (_weibo.getAppConfig().getAutoLoadImageMethod())
						{
							case ShowStatusImage.ONLY_WIFI:
								if (Function.isWiFiConnected()) {refreshStatusImages();}
								break;
							case ShowStatusImage.ALWAYS:
								refreshStatusImages();
								break;
						}
					}
				});
			}
		}
	}

	private synchronized void refreshUserListIcons()
    {
		_queueAvatar.removeAll();

		UiApplication.getUiApplication().invokeLater(new Runnable()
		{
			public void run()
			{
				StatusListStyleButtonField item;

				for (int i=0; i<_listSet.getFieldCount(); i++)
				{
					Field object = _listSet.getField(i);

					if (object instanceof StatusListStyleButtonField)
					{
						item = (StatusListStyleButtonField) object;

						if (item.getUser() != null)
						{
							if (item.getUser().getAvatarIconData() == null)
							{
								_queueAvatar.execute(new DownloadStatusAvatarImages(_weibo, item));					
							}							
						}
					}
				}
			}
		});
    }

	private synchronized void refreshStatusImages()
    {
		UiApplication.getUiApplication().invokeLater(new Runnable()
		{
			public void run()
			{
				StatusListStyleButtonField item;
				Field object;

				for (int i=0; i<_listSet.getFieldCount(); i++)
				{
					object = _listSet.getField(i);
					if (object instanceof StatusListStyleButtonField)
					{
						item = (StatusListStyleButtonField) object;

						if (item.getStatusImagesUrl() != null)
						{
							int count = item.getStatusImagesUrl().length;

							if (count > 0)
							{
								if (needSmallIcon)
				        		{
				        			if (count > 3)
				        			{
				        				if (count == 4)
				        				{
				        					count = 4;
				        				} else {
				        					count = 3;
				        				}
				        			}
				        		} else {
				        			if (count > 5)
				        			{
				        				if (count == 6)
				        				{
				        					count = 6;
				        				} else {
				        					count = 5;				        					
				        				}
				        			}
				        		}

								for (int j=0; j<count; j++)
								{
									if (item.getStatusImageData(j) == null)
									{
										_queueImage.execute(new DownloadStatusImages(_weibo, item, j, false));
									}
								}								
							}
						} else if (item.getRetweetedImagesUrl() != null) {
							int count = item.getRetweetedImagesUrl().length;

							if (count > 0)
							{
								if (needSmallIcon)
				        		{
				        			if (count > 3)
				        			{
				        				if (count == 4)
				        				{
				        					count = 4;
				        				} else {
				        					count = 3;
				        				}
				        			}
				        		} else {
				        			if (count > 5)
				        			{
				        				if (count == 6)
				        				{
				        					count = 6;
				        				} else {
				        					count = 5;				        					
				        				}
				        			}
				        		}

								for (int j=0; j<count; j++)
								{
									if (item.getRetweetedImageData(j) == null)
									{
										_queueImage.execute(new DownloadStatusImages(_weibo, item, j, true));
									}
								}
							}
						}
					}
				}
			}
		});
    }

	private void showStatusImages()
	{
		StatusListStyleButtonField item;
		Field object;

		if (isStatusObjectWithCheck())
		{
			object = _listSet.getFieldWithFocus();

			if (object instanceof StatusListStyleButtonField)
			{
				item = (StatusListStyleButtonField) object;

				if (item.getStatus().getPicUrls().getCount() > 0 || item.getRetweetedStatus().getPicUrls().getCount() > 0)
				{
					UiApplication.getUiApplication().pushScreen(new ShowPreviewImagesFullScreen(_weibo, item));					
				}
			}
		}
	}

	private void createNewStatus() {UiApplication.getUiApplication().pushScreen(new NewStatusMainScreen(_weibo));}

	private void showRepostStatusScreen(boolean isRetweeted)
	{
		if (isStatusObjectWithCheck())
		{
			//if (_listSet.getFieldCount() > 0)
			//{
				StatusListStyleButtonField item;
				item = (StatusListStyleButtonField) _listSet.getFieldWithFocus();

				if (isRetweeted)
				{
					if (item.getRetweetedStatus() != null)
					{
						UiApplication.getUiApplication().pushScreen(new RepostReplyStatusMainScreen(_weibo, item.getRetweetedStatus(), true));	
					}
				} else {
					UiApplication.getUiApplication().pushScreen(new RepostReplyStatusMainScreen(_weibo, item.getStatus(), true));					
				}
			//}
		}
	}

	private void showReplyStatusScreen(boolean isRetweeted)
	{
		if (isStatusObjectWithCheck() || isCommentObjectWithCheck())
		{
			StatusListStyleButtonField item;
			item = (StatusListStyleButtonField) _listSet.getFieldWithFocus();

			switch (_action)
			{
				case RefreshAction.STATUSMENTIONS:
				case RefreshAction.FRIENDSTIMELINE:
				case RefreshAction.PUBLICTIMELINE:
				case RefreshAction.USERTIMELINE:
				case RefreshAction.FAVORITES:
				case RefreshAction.FAVORITESBYTAGS:
				case RefreshAction.GROUPTIMELINE:
					if (isRetweeted)
					{
						if (item.getRetweetedStatus() != null)
						{
							UiApplication.getUiApplication().pushScreen(new RepostReplyStatusMainScreen(_weibo, item.getRetweetedStatus(), false));
						}
					} else {
						UiApplication.getUiApplication().pushScreen(new RepostReplyStatusMainScreen(_weibo, item.getStatus(), false));	
					}

					break;
				default:
					UiApplication.getUiApplication().pushScreen(new RepostReplyStatusMainScreen(_weibo, item.getComment()));
					break;
			}
		}
	}

	private void showUserHomepage()
	{
		if (_listSet.getFieldCount() > 0)
		{
			StatusListStyleButtonField item = (StatusListStyleButtonField) _listSet.getFieldWithFocus();

			UiApplication.getUiApplication().pushScreen(new HomePageMainScreen(_weibo, item.getUser()));
		}
	}

	private void destroyFavorites()
	{
		if (isFavoriteObjectWithCheck())
		{
			UiApplication.getUiApplication().invokeLater(new Runnable()
			{
				public void run()
				{
					StatusListStyleButtonField item = (StatusListStyleButtonField) _listSet.getFieldWithFocus();
					Hashtable params = new Hashtable();

					params.put("id", item.getIdStr());

					RefreshContentsScreen popupScreen = new RefreshContentsScreen(_weibo, params, RefreshAction.FAVORITESDESTROY);
					UiApplication.getUiApplication().pushModalScreen(popupScreen);

					Favorite favorite = popupScreen.getFavorite();

					if (popupScreen != null) {popupScreen = null;}
					if (favorite != null) {Function.errorDialog("成功取消收藏一条微博！");}
				}
			});
		}
	}

	private void createFavorites()
	{
		if (isStatusObjectWithCheck() && !isFavoriteObject())
		{
			UiApplication.getUiApplication().invokeLater(new Runnable()
			{
				public void run()
				{
					StatusListStyleButtonField item = (StatusListStyleButtonField) _listSet.getFieldWithFocus();
					Hashtable params = new Hashtable();

					params.put("id", item.getIdStr());

					RefreshContentsScreen popupScreen = new RefreshContentsScreen(_weibo, params, RefreshAction.FAVORITESCREATE);
					UiApplication.getUiApplication().pushModalScreen(popupScreen);

					Favorite favorite = popupScreen.getFavorite();

					if (popupScreen != null) {popupScreen = null;}
					if (favorite != null) {Function.errorDialog("成功收藏一条微博！");}
				}
			});
		}
	}

	/**
	 * 显示微博正文中的链接和用户列表窗口
	 */
	private void showLinksOrUsers(boolean isRetweeted, boolean isLinks)
	{
		String fullString;
		StatusListStyleButtonField item;

		if (!isRetweeted)
		{
			if (isStatusObjectWithCheck())
	    	{
				item = (StatusListStyleButtonField) _listSet.getFieldWithFocus();
				fullString = item.getStatus().getText();
	    	} else {return;}
		} else {
			if (hasRetweetedStatus())
			{
				item = (StatusListStyleButtonField) _listSet.getFieldWithFocus();
				fullString = "@" + item.getRetweetedStatus().getUser().getScreenName() + " :" + item.getRetweetedStatus().getText();
			} else {return;}
		}

		RE re = new RE();

		if (isLinks)
		{
			re = new RE("http(s)?://[\\w.][/\\w(.)=?]+(/)?");
		} else {
			re = new RE("@[^.,:;!?（）\\s#@。，：；！？]{2,20}");
		}

		if (re.match(fullString))
		{
			Vector result = re.getMatchResult();

			if (result.size() > 0)
			{
				if (result.size() == 1)
				{
					if (isLinks)
					{
						BrowserSession browser = Browser.getDefaultSession();
			    		browser.displayPage((String) result.elementAt(0));
					} else {
						UiApplication.getUiApplication().pushScreen(new ShowUsersLinksPopupScreen(_weibo, result, isLinks));
					}
				} else {
					UiApplication.getUiApplication().pushScreen(new ShowUsersLinksPopupScreen(_weibo, result, isLinks));
				}
			}
		}
	}

	/**
	 * 根据窗口实例传递进来的action判断是否为Status对象，并检查listSet是否为空，Status对象可以评论、转发
	 */
	private boolean isStatusObjectWithCheck()
	{
		boolean result = false;

		if (_listSet.getFieldCount() > 0) {result = ((_action >= 0) && (_action <= 4) || _action == RefreshAction.FAVORITES || _action == RefreshAction.FAVORITESBYTAGS) || _action == RefreshAction.GROUPTIMELINE;} 

		return result;
	}

	/**
	 * 根据窗口实例传递进来的action判断是否为Comment对象，并检查listSet是否为空，Comment对象只可以评论<br />
	 * 这里不包括判断是否有 我发出的评论 一项
	 */
	private boolean isCommentObjectWithCheck()
	{
		boolean result = false;

		if (_listSet.getFieldCount() > 0) {result = ((_action == 5) || (_action == 6));}

		return result;
	}

	private boolean isFavoriteObjectWithCheck()
	{
		boolean result = false;

		if (_listSet.getFieldCount() > 0) {result = ((_action == RefreshAction.FAVORITES) || (_action == RefreshAction.FAVORITESBYTAGS));}

		return  result;
	}

	/**
	 * 根据窗口实例传递进来的action判断是否为Status对象，Status对象可以评论、转发
	 */
	private boolean isStatusObject() {return ((_action >= 0) && (_action <= 4) || _action == RefreshAction.GROUPTIMELINE);}

	/**
	 * 根据窗口实例传递进来的action判断是否为Comment对象，Comment对象只可以评论<br />
	 * 这里包括判断是否有 我发出的评论 一项
	 */
	private boolean isCommentObject() {return ((_action >= 5) && (_action <= 7));}

	private boolean isFavoriteObject() {return  ((_action == RefreshAction.FAVORITES) || (_action == RefreshAction.FAVORITESBYTAGS));}

	private boolean hasRetweetedStatus()
	{
		boolean result = false;

		if (_listSet.getFieldCount() > 0)
		{
			StatusListStyleButtonField item = (StatusListStyleButtonField) _listSet.getFieldWithFocus();
			result = item.getStatus().getRetweetedStatus() != null;
		}

		return result;
	}

	private String getResString(int key) {return _bundle.getString(key);}

	MenuItem menuRefresh = new MenuItem(_bundle, MENU_REFRESH, 100, 10)
	{
		public void run() {refreshHomePage();}
	};

	MenuItem menuUserHomepage = new MenuItem(_bundle, MENU_SHOW_USER_HOMEPAGE, 100, 20)
	{
		public void run(){showUserHomepage();} 
	};

	MenuItem menuRefreshStatusImage = new MenuItem(new StringProvider("显示配图"), 100, 30)
    {
    	public void run() {refreshStatusImages();} 
    };

    MenuItem menuShowStatusImage = new MenuItem(new StringProvider("查看图片(I\u0332)"), 100, 40)
    {
    	public void run() {showStatusImages();}
    };

    MenuItem menuFavoritesCreate = new MenuItem(new StringProvider("收藏(V\u0332)"), 100, 70)
    {
    	public void run() {createFavorites();}
    };

    MenuItem menuFavoritesDestroy = new MenuItem( new StringProvider("取消收藏"), 100, 70)
    {
    	public void run() {destroyFavorites();}
    };

	MenuItem menuRepostStatus = new MenuItem(_bundle, MENU_SHOW_REPOST_STATUS_SCREEN, 200, 10)
    {
    	public void run() {showRepostStatusScreen(false);}
    };

    MenuItem menuReplyStatus = new MenuItem(_bundle, MENU_SHOW_REPLY_STATUS_SCREEN, 200, 20)
    {
    	public void run() {showReplyStatusScreen(false);}
    };

    MenuItem menuStatusLinks = new MenuItem(_bundle, MENU_SHOW_LINKS_LIST, 200, 30)
    {
    	public void run() {showLinksOrUsers(false, true);} 
    };

    MenuItem menuStatusUsers = new MenuItem(_bundle, MENU_SHOW_USERS_LINK, 200, 40)
    {
    	public void run() {showLinksOrUsers(false, false);} 
    };

    MenuItem menuRepostRetweetedStatus = new MenuItem(_bundle, MENU_SHOW_RETWEETED_REPOST_STATUS_SCREEN, 200, 10)
    {
    	public void run() {showRepostStatusScreen(true);}
    };

    MenuItem menuReplyRetweetedStatus = new MenuItem(_bundle, MENU_SHOW_RETWEETED_REPLY_STATUS_SCREEN, 200, 20)
    {
    	public void run() {showReplyStatusScreen(true);}
    };

    MenuItem menuRetweetedLinks = new MenuItem(_bundle, MENU_SHOW_RETWEETED_LINKS_LIST, 200, 30)
    {
    	public void run() {showLinksOrUsers(true, true);} 
    };

    MenuItem menuRetweetedUsers = new MenuItem(_bundle, MENU_SHOW_RETWEETED_USERS_LIST, 200, 40)
    {
    	public void run() {showLinksOrUsers(true, false);} 
    };

    MenuItem menuExit = new MenuItem(_bundle, MENU_EXIT, 100, 70)
    {
    	public void run() {Function.showExitDialog();}
    };

    MenuItem[] menuStatusLinksItem;

    protected void makeMenu(Menu menu, int instance)
    {
    	SubMenu menuStatus = new SubMenu(null, "微博", 100, 50);
    	menuStatus.add(menuRepostStatus);
    	menuStatus.add(menuReplyStatus);
    	menuStatus.add(menuStatusLinks);
    	menuStatus.add(menuStatusUsers);
    	menuStatus.addSeparator();

    	SubMenu menuRetweeted = new SubMenu(null, "原文", 100, 60);
    	menuRetweeted.add(menuRepostRetweetedStatus);
    	menuRetweeted.add(menuReplyRetweetedStatus);
    	menuRetweeted.addSeparator();
    	menuRetweeted.add(menuRetweetedLinks);
    	menuRetweeted.add(menuRetweetedUsers);

    	menu.add(menuRefresh);
    	menu.addSeparator();

    	if (_action < 7)
    	{
    		if (_listSet.getFieldCount() > 0)
    		{
            	menu.add(menuUserHomepage);
            	menu.addSeparator();
    		}
    	}

    	if (isStatusObjectWithCheck())
    	{
    		menu.add(menuRefreshStatusImage);
    		menu.add(menuShowStatusImage);
			menu.addSeparator();

    		menu.add(menuStatus);

    		if (hasRetweetedStatus()) {menu.add(menuRetweeted);}

    		menu.addSeparator();
    		menu.add(isFavoriteObject() ? menuFavoritesDestroy : menuFavoritesCreate);
    		menu.addSeparator();
    	} else if (isCommentObjectWithCheck()) {
    		menuReplyStatus.setText(new StringProvider(getResString(MENU_STATUS_REPLY)));
    		menu.add(menuReplyStatus);
    		menu.addSeparator();
    	}

    	super.makeMenu(menu, instance);
    }

    protected boolean navigationMovement(int dx, int dy, int status, int time)
    {
    	if (_listSet.getFieldCount() > 0 && _listSet.getFieldWithFocus() instanceof StatusListStyleButtonField)
    	{
    		StatusListStyleButtonField item = (StatusListStyleButtonField) _listSet.getFieldWithFocus();

    		if (item != null)
    		{
            	if (Math.abs(dx) < Math.abs(dy))
            	{
            		if (time - _lastMovementTime > 300)
            		{
            			if (dy < 0)
            			{
            				if (_foreground.getVerticalScroll() > item.getContentTop())
        	    			{
            					int step = _foreground.getVerticalAdjustment().getPageStepSize();
            					_foreground.getVerticalAdjustment().setPageStep(_foreground.getVerticalScroll() - item.getContentTop());
            					_foreground.getVerticalAdjustment().pageStepDown();
            					_foreground.getVerticalAdjustment().setPageStep(step);
        	    			} else {
        	    				_lastMovementTime = time;
        	    				return super.navigationMovement(dx, dy, status, time);
        	    			}
            			} else if (dy > 0) {
            				if (item.getContentHeight() < _listSet.getVisibleHeight())
            				{
            					_lastMovementTime = time;
            					return super.navigationMovement(dx, dy, status, time);
            				} else {
            	    			if (_foreground.getVerticalScroll() == item.getContentTop())
            	    			{
                					int step = _foreground.getVerticalAdjustment().getPageStepSize();
                					_foreground.getVerticalAdjustment().setPageStep(item.getContentHeight() - _foreground.getVisibleHeight());
                					_foreground.getVerticalAdjustment().pageStepUp();
                					_foreground.getVerticalAdjustment().setPageStep(step);
            	    			} else {
            	    				_lastMovementTime = time;
            	    				return super.navigationMovement(dx, dy, status, time);
            	    			}
            				}
            			}
            		}
            	}

    			_lastMovementTime = time;
    			return true;
    		}
    	}

    	return super.navigationMovement(dx, dy, status, time);
    }

    protected boolean keyChar(char character, int status, int time)
    {
    	switch (character)
    	{
    		case Characters.SPACE:
    			if (_listSet.getFieldCount() > 0 && _listSet.getFieldWithFocusIndex() < _listSet.getFieldCount())
    			{
    				_listSet.getField(_listSet.getFieldWithFocusIndex() + 1).setFocus();
    			}
    			return true;
    		case Characters.LATIN_CAPITAL_LETTER_C:
    		case Characters.LATIN_SMALL_LETTER_C:
    			createNewStatus();
    			return true;
			case Characters.LATIN_CAPITAL_LETTER_R:
			case Characters.LATIN_SMALL_LETTER_R:
				refreshHomePage();
				return true;
			case Characters.LATIN_CAPITAL_LETTER_T:
			case Characters.LATIN_SMALL_LETTER_T:
				if (_listSet.getFieldCount() > 0) {_listSet.getField(0).setFocus();}
				return true;
			case Characters.LATIN_CAPITAL_LETTER_B:
			case Characters.LATIN_SMALL_LETTER_B:
				if (_listSet.getFieldCount() > 0) {_listSet.getField(_listSet.getFieldCount() - 1).setFocus();}
				return true;
			case Characters.LATIN_CAPITAL_LETTER_I:
			case Characters.LATIN_SMALL_LETTER_I:
				showStatusImages();
				return true;
			case Characters.LATIN_CAPITAL_LETTER_D:
			case Characters.LATIN_SMALL_LETTER_D:
				showReplyStatusScreen(false);
				return true;
			case Characters.LATIN_CAPITAL_LETTER_F:
			case Characters.LATIN_SMALL_LETTER_F:
				showRepostStatusScreen(false);					
				return true;
			case 'u':
				showUserHomepage();
				return true;
			case Characters.LATIN_CAPITAL_LETTER_A:
			case Characters.LATIN_SMALL_LETTER_A:
				return true;
			case Characters.LATIN_CAPITAL_LETTER_Q:
			case Characters.LATIN_SMALL_LETTER_Q:
				Function.showExitDialog();
				return true;
			case Characters.DIGIT_FIVE:
				showReplyStatusScreen(true);
				return true;
			case Characters.DIGIT_SIX:
				showRepostStatusScreen(true);
				return true;
			case 'l':
				showLinksOrUsers(false, true);
				break;
			case 'k':
				showLinksOrUsers(false, false);
				break;
			case Characters.QUOTATION_MARK:
				showLinksOrUsers(true, true);
				break;
			case Characters.APOSTROPHE:
			case '＇':
				showLinksOrUsers(true, false);
				break;
			case Characters.LATIN_CAPITAL_LETTER_P:
			case Characters.LATIN_SMALL_LETTER_P:
				UiApplication.getUiApplication().pushScreen(new ShowTestStatusesMainScreen(_weibo, _statusWrapper));
				return true;
			case Characters.LATIN_CAPITAL_LETTER_V:
			case Characters.LATIN_SMALL_LETTER_V:
				createFavorites();
				return true;
		}

    	return super.keyChar(character, status, time);
    }

    public boolean onClose()
    {
    	_queueAvatar.removeAll();
    	_queueImage.removeAll();

    	return super.onClose();
    }

    protected boolean onSavePrompt() {return true;}
}